/**
 *  * 图床服务 sm.ms 的接口
 *   * 除了 sm.ms 官方的接口, 还增加了图像 resize 功能
 *    **/

const rp = require('request-promise');
const fs = require('fs');
const gm = require('gm');
const imageMagick = gm.subClass({ imageMagick: true });

let smmsx = {
	api: {
		upload: 'https://sm.ms/api/upload',
		list: 'https://sm.ms/api/list',
		clear: 'https://sm.ms/api/clear'
	},

	// 上传文件至图床
	upload(filename){
		let formData = {
			smfile: fs.createReadStream(filename),
			ssl: 1,
			format: 'json'
		};
		return rp.post({url: this.api.upload, 
			headers: {
			    'User-Agent': 'request'
			  },
  			formData: formData});
	},
	list(){
		// TODO
	},
	remove(){
		// TODO
	},
	clear(){
		// TODO
	},
	resize(filename,distfile, width, height){
		if (!width && !height){
			return filename;
		}
		return new Promise((resolve, reject)=>{
			imageMagick(filename).resize(width, height).write(distfile, (err, stdout, stderr, command)=>{
				if (err){
					reject(err);
				} else {
					resolve(stdout);
				}
			})
		});
	}
}

module.exports = smmsx;

// test
//const imgsrc = 'https://static.cnbetacdn.com/thumb/article/2018/0228/488b5dfde180231.jpeg';
//const thumb = '/home/linglq/tmp/smmsx_' + (new Date().getTime()) + '_' + Math.random() + '.jpg';
//smmsx.resize(imgsrc, thumb, 200, null).then(stdout=>{
//	console.log(stdout);
//	smmsx.upload(thumb)
//		.then(res=>{
//                	console.log(res)
//        	})  
//        	.catch(err=>{
//                	console.log(err)
//        	})	
//})
